#include "Game.h"

const int WINDOW_WIDTH = 800;
const int WINDOW_HEIGHT = 600;

/*-----------------------------------------------------------------------------------------------*/
Game::Game(HINSTANCE hInstance):
   m_pHInstance(hInstance)
{
   m_console.create();
}
/*-----------------------------------------------------------------------------------------------*/
bool Game::start()
{
   m_pWindow = new Window(m_pHInstance);

   if ( !m_pWindow->Create(WINDOW_WIDTH, WINDOW_HEIGHT) )
   {
      std::cout << "error creating window" << std::endl;
      return false;
   }

   m_pRenderer = new Renderer();

   if ( !m_pRenderer->init( m_pWindow->GetHwnd()) )
   {
      std::cout << "Failed to init Renderer" << std::endl;
      return false; 
   }

   m_pImporter = new Importer(m_pRenderer);

   m_pInput = new DirectInput(m_pHInstance , m_pWindow->GetHwnd());
   if(!m_pInput->init())
   {
      std::cout << "Init Input Failed" << std::endl;
      return false;
   }

   m_timer.FirstMeasure();

   return onStart();
}
/*-----------------------------------------------------------------------------------------------*/
void Game::loop()
{
   MSG msg;
   ZeroMemory(&msg, sizeof(MSG));

   while ( msg.message != WM_QUIT && onLoop() )
   {
      if ( PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE) )
      {
         TranslateMessage(&msg);
         DispatchMessage(&msg);
      }

      
      //loop code down here
      m_pRenderer->beginFrame();
      
      updateScenes();
      drawScenes();
      
      onDraw();

      m_pRenderer->endFrame();
      m_pRenderer->present(m_pWindow->GetHwnd());
      
      m_pInput->reacquire();

      //std::cout << m_timer.GetFPS() << std::endl;

      m_timer.Measure();
   }
}
/*-----------------------------------------------------------------------------------------------*/
bool Game::shutDown()
{
   m_pInput->deinit();
   
   delete m_pWindow;
   delete m_pRenderer;
   delete m_pImporter;
   delete m_pInput;

   return onShutDown();
}
/*-----------------------------------------------------------------------------------------------*/
void Game::addScene(Scene* scene)
{
   m_sceneMap[scene->getName()] = scene;
}
/*-----------------------------------------------------------------------------------------------*/
void Game::updateScenes()
{
   std::map<std::string, Scene*>::iterator it;

   for (it = m_sceneMap.begin(); it != m_sceneMap.end(); ++it)
   {
      if (it->second->isUpdateable())
      {
         it->second->update(m_timer.GetDT());
      }
   }
}
/*-----------------------------------------------------------------------------------------------*/
void Game::drawScenes()
{
   std::map<std::string, Scene*>::iterator it;

   for (it = m_sceneMap.begin(); it != m_sceneMap.end(); ++it)
   {
      if (it->second->isDrawable())
      {
         it->second->draw(m_pRenderer);
      }
   }
}